// common.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mysql.h>
#include "common.h"

MYSQL *do_connect(char *host_name, char *user_name, char *password, char *db_name,
                  unsigned int port_num, char *socket_name, unsigned int flags) {

	MYSQL *conn = mysql_init(NULL);  /* pointer to connection handler */	
	if(conn == NULL) {
		print_error(NULL, "mysql_init() failed!\n");
		return NULL;
	}
	if(mysql_real_connect(conn, host_name, user_name, password, db_name, port_num,
                          socket_name, flags) == NULL) {
		print_error(conn,"mysql_real_connect() failed!"); 
		return NULL;
	}
	if(db_name != NULL) {
		if(mysql_select_db(conn, db_name) != 0) {
			print_error(conn,"mysql_select_db() failed");
			mysql_close(conn);
			return NULL;
		}
	}
	fprintf(stdout, "Connection succsessfull!\n");
	return conn;
}
	
void do_disconnect(MYSQL* conn) {
	mysql_close(conn);
}

void process_query(MYSQL *conn, char *query, char *action, char **res) {

	MYSQL_RES *res_set;
	// The query failed
	if(mysql_query(conn, query) != 0) {
		print_error(conn, "process_query() failed");
		return;
	}
	/* The query succeded - determine whether or no it returns data */
	res_set = mysql_store_result(conn);
	/* No result set was returned */
	if(res_set == NULL) {
		/* An error occurred, a result set was expected */
		if(mysql_field_count(conn) > 0) {
			print_error(conn, "Problem processing result set!");
		} 
		/* Query was processed ok, but no data was returned */
		else {
			printf("%lu rows afected\n", (unsigned long) mysql_affected_rows(conn));
		}
	/* A result set was retunred */
	} else {
		/* Decide what action to take */
		if(action == NULL) show_result_set(conn, res_set);
		else if(strcmp(action, "get_path_and_ip") == 0) process_select(conn, res_set, res);
		mysql_free_result(res_set);
	}
}

void print_error(MYSQL *conn, char *message) {
	fprintf(stderr, "%s\n", message);
	if(conn != NULL) {
		fprintf(stderr, "Error %u (%s)\n", mysql_errno(conn), mysql_error(conn));
	}
}

void show_result_set(MYSQL *conn, MYSQL_RES *res_set) {
	MYSQL_ROW row;
	unsigned int i;
	while((row = mysql_fetch_row(res_set)) != NULL) {
		for(i=0; i < mysql_num_fields(res_set); i++) {
			fputc('\t', stdout);
			printf("%s", row[i] != NULL ? row[i] : "NULL");
		}
		fputc('\n', stdout);
	}
	if(mysql_errno(conn) != 0) print_error(conn, "mysql_fetch_row() failed!");
	else printf("%lu rows returned\n", (unsigned long) mysql_num_rows(res_set));
}

void process_select(MYSQL *conn, MYSQL_RES *res_set, char **res) {
	MYSQL_ROW row;
	unsigned int i;
	while((row = mysql_fetch_row(res_set)) != NULL) {
		for(i=0; i< mysql_num_fields(res_set); i++) {
			res[i] = malloc(sizeof(char)*strlen(row[i])+1);
			strcpy(res[i], row[i]);
			printf("res[%i] = %s\n", i, res[i]);
		}
	}
	if(mysql_errno(conn) != 0) print_error(conn, "mysql_fetch_row() failed!");
	else printf("%lu rows returned\n", (unsigned long) mysql_num_rows(res_set));
}
